{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "c4915595",
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        timer = time.time\n",
    "\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "# 获取access_token的函数\n",
    "def fetch_token(API_KEY,SECRET_KEY):\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request('http://aip.baidubce.com/oauth/2.0/token', post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "    result = json.loads(result_str)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "# 语音识别函数      \n",
    "def asr(token,AUDIO_FILE,CUID='123456PYTHON',DEV_PID=1537,RATE=16000):\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    params_query = urlencode(params);\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + AUDIO_FILE[-3:] + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "\n",
    "    url = 'http://vop.baidu.com/server_api' + \"?\" + params_query\n",
    "    req = Request('http://vop.baidu.com/server_api' + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "1e503051",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting speech-recognition-python\n",
      "  Using cached speech_recognition_python-3.9.9-py3-none-any.whl\n",
      "Requirement already satisfied: nltk in d:\\anaconda3\\lib\\site-packages (from speech-recognition-python) (3.6.1)\n",
      "Collecting pocketsphinx\n",
      "  Using cached pocketsphinx-0.1.15.tar.gz (29.1 MB)\n",
      "Collecting google-trans-new\n",
      "  Using cached google_trans_new-1.1.9-py3-none-any.whl (9.2 kB)\n",
      "Requirement already satisfied: numpy in d:\\anaconda3\\lib\\site-packages (from speech-recognition-python) (1.20.1)\n",
      "Requirement already satisfied: tqdm in d:\\anaconda3\\lib\\site-packages (from nltk->speech-recognition-python) (4.59.0)\n",
      "Requirement already satisfied: click in d:\\anaconda3\\lib\\site-packages (from nltk->speech-recognition-python) (7.1.2)\n",
      "Requirement already satisfied: joblib in d:\\anaconda3\\lib\\site-packages (from nltk->speech-recognition-python) (1.0.1)\n",
      "Requirement already satisfied: regex in d:\\anaconda3\\lib\\site-packages (from nltk->speech-recognition-python) (2021.4.4)\n",
      "Building wheels for collected packages: pocketsphinx\n",
      "  Building wheel for pocketsphinx (setup.py): started\n",
      "  Building wheel for pocketsphinx (setup.py): finished with status 'error'\n",
      "  Running setup.py clean for pocketsphinx\n",
      "Failed to build pocketsphinx\n",
      "Installing collected packages: pocketsphinx, google-trans-new, speech-recognition-python\n",
      "    Running setup.py install for pocketsphinx: started\n",
      "    Running setup.py install for pocketsphinx: finished with status 'error'\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  ERROR: Command errored out with exit status 1:\n",
      "   command: 'D:\\Anaconda3\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\86133\\\\AppData\\\\Local\\\\Temp\\\\pip-install-da5uwgp5\\\\pocketsphinx_c6672447e6e04cff95ca3406b8964ff2\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\86133\\\\AppData\\\\Local\\\\Temp\\\\pip-install-da5uwgp5\\\\pocketsphinx_c6672447e6e04cff95ca3406b8964ff2\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' bdist_wheel -d 'C:\\Users\\86133\\AppData\\Local\\Temp\\pip-wheel-bwzmcxp2'\n",
      "       cwd: C:\\Users\\86133\\AppData\\Local\\Temp\\pip-install-da5uwgp5\\pocketsphinx_c6672447e6e04cff95ca3406b8964ff2\\\n",
      "  Complete output (6 lines):\n",
      "  running bdist_wheel\n",
      "  running build_ext\n",
      "  building 'sphinxbase._sphinxbase' extension\n",
      "  swigging deps/sphinxbase/swig/sphinxbase.i to deps/sphinxbase/swig/sphinxbase_wrap.c\n",
      "  swig.exe -python -modern -threads -Ideps/sphinxbase/include -Ideps/sphinxbase/include/sphinxbase -Ideps/sphinxbase/include/win32 -Ideps/sphinxbase/swig -outdir sphinxbase -o deps/sphinxbase/swig/sphinxbase_wrap.c deps/sphinxbase/swig/sphinxbase.i\n",
      "  error: command 'swig.exe' failed: No such file or directory\n",
      "  ----------------------------------------\n",
      "  ERROR: Failed building wheel for pocketsphinx\n",
      "    ERROR: Command errored out with exit status 1:\n",
      "     command: 'D:\\Anaconda3\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\86133\\\\AppData\\\\Local\\\\Temp\\\\pip-install-da5uwgp5\\\\pocketsphinx_c6672447e6e04cff95ca3406b8964ff2\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\86133\\\\AppData\\\\Local\\\\Temp\\\\pip-install-da5uwgp5\\\\pocketsphinx_c6672447e6e04cff95ca3406b8964ff2\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record 'C:\\Users\\86133\\AppData\\Local\\Temp\\pip-record-be5xod3i\\install-record.txt' --single-version-externally-managed --compile --install-headers 'D:\\Anaconda3\\Include\\pocketsphinx'\n",
      "         cwd: C:\\Users\\86133\\AppData\\Local\\Temp\\pip-install-da5uwgp5\\pocketsphinx_c6672447e6e04cff95ca3406b8964ff2\\\n",
      "    Complete output (6 lines):\n",
      "    running install\n",
      "    running build_ext\n",
      "    building 'sphinxbase._sphinxbase' extension\n",
      "    swigging deps/sphinxbase/swig/sphinxbase.i to deps/sphinxbase/swig/sphinxbase_wrap.c\n",
      "    swig.exe -python -modern -threads -Ideps/sphinxbase/include -Ideps/sphinxbase/include/sphinxbase -Ideps/sphinxbase/include/win32 -Ideps/sphinxbase/swig -outdir sphinxbase -o deps/sphinxbase/swig/sphinxbase_wrap.c deps/sphinxbase/swig/sphinxbase.i\n",
      "    error: command 'swig.exe' failed: No such file or directory\n",
      "    ----------------------------------------\n",
      "ERROR: Command errored out with exit status 1: 'D:\\Anaconda3\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\86133\\\\AppData\\\\Local\\\\Temp\\\\pip-install-da5uwgp5\\\\pocketsphinx_c6672447e6e04cff95ca3406b8964ff2\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\86133\\\\AppData\\\\Local\\\\Temp\\\\pip-install-da5uwgp5\\\\pocketsphinx_c6672447e6e04cff95ca3406b8964ff2\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record 'C:\\Users\\86133\\AppData\\Local\\Temp\\pip-record-be5xod3i\\install-record.txt' --single-version-externally-managed --compile --install-headers 'D:\\Anaconda3\\Include\\pocketsphinx' Check the logs for full command output.\n"
     ]
    }
   ],
   "source": [
    "pip install speech-recognition-python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61b8dc30",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "4df5a00b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: pipwin in d:\\anaconda3\\lib\\site-packages (0.5.2)\n",
      "Requirement already satisfied: js2py in d:\\anaconda3\\lib\\site-packages (from pipwin) (0.71)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in d:\\anaconda3\\lib\\site-packages (from pipwin) (4.9.3)\n",
      "Requirement already satisfied: packaging in d:\\anaconda3\\lib\\site-packages (from pipwin) (20.9)\n",
      "Requirement already satisfied: six in d:\\anaconda3\\lib\\site-packages (from pipwin) (1.15.0)\n",
      "Requirement already satisfied: docopt in d:\\anaconda3\\lib\\site-packages (from pipwin) (0.6.2)\n",
      "Requirement already satisfied: requests in d:\\anaconda3\\lib\\site-packages (from pipwin) (2.25.1)\n",
      "Requirement already satisfied: pyprind in d:\\anaconda3\\lib\\site-packages (from pipwin) (2.11.3)\n",
      "Requirement already satisfied: pySmartDL>=1.3.1 in d:\\anaconda3\\lib\\site-packages (from pipwin) (1.3.4)\n",
      "Requirement already satisfied: soupsieve>1.2 in d:\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.2.1)\n",
      "Requirement already satisfied: pyjsparser>=2.5.1 in d:\\anaconda3\\lib\\site-packages (from js2py->pipwin) (2.7.1)\n",
      "Requirement already satisfied: tzlocal>=1.2 in d:\\anaconda3\\lib\\site-packages (from js2py->pipwin) (4.2)\n",
      "Requirement already satisfied: tzdata in d:\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (2022.1)\n",
      "Requirement already satisfied: pytz-deprecation-shim in d:\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (0.1.0.post0)\n",
      "Requirement already satisfied: backports.zoneinfo in d:\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (0.2.1)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in d:\\anaconda3\\lib\\site-packages (from packaging->pipwin) (2.4.7)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (1.26.4)\n",
      "Requirement already satisfied: chardet<5,>=3.0.2 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (4.0.0)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (2020.12.5)\n",
      "Requirement already satisfied: idna<3,>=2.5 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (2.10)\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install pipwin"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "fb0476b6",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-35-cd5d3650b53e>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-35-cd5d3650b53e>\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m    pipwin install PyAudio\u001b[0m\n\u001b[1;37m           ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "pipwin install PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "378c18fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = 'tkWeaZVc9Tf5KqQZ2Vj4rssa'\n",
    "SECRET_KEY = '9BZUoDcwoagxXo7qFrkUrXxlUYxwxo9E'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "a1a2b062",
   "metadata": {},
   "outputs": [],
   "source": [
    "from bdasr import fetch_token,asr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "5d4fe6e7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SUCCESS WITH TOKEN: 24.0e21c0063fa0a78914f934e6042c1aee.2592000.1655349728.282335-25345353 ; EXPIRES IN SECONDS: 2592000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'24.0e21c0063fa0a78914f934e6042c1aee.2592000.1655349728.282335-25345353'"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "LIANG_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "LIANG_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "6f2d4401",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "0030a68e",
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "unexpected EOF while parsing (<ipython-input-40-17472fe21a16>, line 9)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-40-17472fe21a16>\"\u001b[1;36m, line \u001b[1;32m9\u001b[0m\n\u001b[1;33m    }\u001b[0m\n\u001b[1;37m     ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m unexpected EOF while parsing\n"
     ]
    }
   ],
   "source": [
    "TL_KEY = ''\n",
    "TL_URL = ''\n",
    "payload={\n",
    "    \"reqType\":0,\n",
    "    \"perception\":{\n",
    "        \"inputText\":{\n",
    "            \"text\":\"苹果英语怎么说\"\n",
    "    \n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "7d7def3f",
   "metadata": {},
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'speech_recognition'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-42-bc488f3e16dc>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mimport\u001b[0m \u001b[0mspeech_recognition\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mr\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mspeech_recognition\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mRecognizer\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[1;32mwith\u001b[0m \u001b[0mspeech_recognition\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mMicrophone\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0msource\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'speech_recognition'"
     ]
    }
   ],
   "source": [
    "import speech_recognition\n",
    "\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "    \n",
    "LIANG_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_ouput = eval(asr(LIANG_token,'1.wav'))['result'][0]\n",
    "\n",
    "TL_API(TL_KEY,asr_output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "614f04ab",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
